<?php

namespace App\Http\Controllers\Wechat\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\UserEnvelopRequest;
use App\Repos\UserEnvelopeRepo;
use App\Services\RedisService;
use App\Repos\CouponRepo;
use App\Repos\UserCouponRepo;
use App\Models\Tensecond;
use App\Repos\OrderRepo;
use Log;

class UserEnvelopController extends Controller
{
    public function index(UserEnvelopRequest $request)
    {
    	$rs['status'] = false;
    	$where['user_id'] = $request->user_id;    	
    	$where['is_used'] = 0;  // 未被使用得券
        if($request->shop_id) {
            $where['shop_id'] = $request->shop_id;
        }
    	$list = UserEnvelopRepo::getPages($where,$num=10);
    	if($list) {
    		$rs['status'] = true;
    		$rs['data'] = $list;
    		return response()->json($rs)->setEncodingOptions(JSON_NUMERIC_CHECK);
    	}
    	return response()->json($rs);
    }

    public function getTensecondTimes(UserEnvelopRequest $request)
    {   
        $rs['status'] = true;
        $date    = date('Ymd');
        $datekey = 'fruit:users:10s:'.$request->user_id.$date;
        // 今天还有几次机会
        $times = RedisService::get($datekey);
        if($times==''){
            RedisService::set($datekey,1,strtotime('tomorrow')); 
            $times = 1;
            $rs['data'] = $times;
            return response()->json($rs);
        } 
        $rs['data'] = $times;

        // 只能查询一次。
        RedisService::decr($datekey);
        return response()->json($rs);

    }

    /**
     * 拍十秒红包
     * 非 订单拍十秒 ，每天只能拍一次，订单红包要验证是否拍过
     */
    public function getEnvelop(UserEnvelopRequest $request)
    {
        $rs['status'] = false;
        $validatedData = $request->validate([
            'shop_id' => 'required',  
            'date'    => 'required',   
            'type'    => 'required',   
        ]);
        $date = date('Ymd');
        $datekey = 'fruit:users:10s:'.$request->user_id.$date;
        // 今天还有几次机会
        $times = RedisService::get($datekey);
       
        // 如果次数小于1 并且没有订单号
        if($times<1&&empty($request->order_code)) {
            $rs['msg'] = '您今天已经参加过活动了';
            return response()->json($rs);
        }

        $second = $request->second;
        Log::info('拍十秒：'.$second);
        // 9秒以下 10.2秒以上 不中奖
        if($second<9||$second>10.2) {
            RedisService::decr($datekey);
            $rs['status'] = true;
            $rs['data']['result'] = 0;
            $rs['msg']            = '手速太慢没有中奖' ;
            return response()->json($rs);
        }

       
        
        // 如果有订单编号 那么要先查查这个订单有没有参与过拍十秒抽红包
        if($request->order_code) {
            $where['code']    = $request->order_code;
            $where['user_id'] = $request->user_id;
            $result = OrderRepo::tenSeconds($where);
            if($result['status'] == false) {
                $rs['msg'] = $result['msg'];
                return response()->json($rs);
            }
        } else {
            // 没有订单号就是每天第一次拍十秒
            $date = date('Ymd');
            if($date!=$request->date) {
                $rs['msg'] = '日期错误';
                return response()->json($rs);
            }      


                 
        }

        // 9.5秒 到 10.5秒随机
        // 拍十秒的设置
        $ten = Tensecond::first();
        if($second>9.5&&$second<10.5&&$second!=10) {        
            
            $num = mt_rand(1,$ten->base_num);
            if($num>$ten->geted_num) {
                RedisService::decr($datekey);
                $rs['status'] = true;
                $rs['data']['result'] = 0;
                $rs['msg']            = '没有获得红包' ;
                return response()->json($rs);
            }
        }

        $shop_id = $request->shop_id;

        $ue = null;
        $uc = null;
        $msg = '';
        $flag = '';

        if($ten->is_envelop==1&&$second=10) {
            $key     = 'fruit:shops:envelops:'.$shop_id;
            $redis_envelop = RedisService::lpop($key);
            if(!$redis_envelop) {
                // 没有红包就发优惠券
                $rs['msg'] = '没有红包了';
                Log::warning('商户：'.$shop_id.',红包用完');
                //return response()->json($rs);
            } else {
                $envelop = json_decode($redis_envelop);
            
                $ue = array_only($request->pure(),['order_code','type','user_id']);
               
                $ue['openid']  = $request->user->openid;
                $ue['shop_envelope_id'] = $envelop->id;
                $ue['money']            = $envelop->money;
                $ue['shop_id'] = $shop_id;
                $ue['type'] = 3; // 拍十秒
               // 拍十秒直接发现金 所以先注释掉下面的一行
                $flag = UserEnvelopeRepo::create($ue); 
                
                array_pull($ue,'openid')  ;  
            }
               
        }
        


        // 发优惠券
        
        if($ten->is_coupon==1) {
             $coupon = CouponRepo::find(['shop_id'=>$shop_id]);
            if($coupon){
                $uc['user_id']     = $request->user_id;
                $uc['shop_id']     = $shop_id;
                $uc['coupon_id']   = $coupon->id;
                $uc['coupon_name'] = $coupon->name;
                $uc['is_used'] = 0;
                $flag = UserCouponRepo::create($uc); 

            }    
        }
       
        
        if(array_get($flag,'status')==true || $flag) {
            if(object_get($request,'order_code')) {
               OrderRepo::changeTenSecondStatus($request->order_code); 
            }
            
                     
            $rs['status'] = true;
            $rs['data']['result'] = 1;

            //$rs['data']['msg']     = '恭喜您拍的红包'.array_get($ue,'money').'元';
            $rs['data']['envelop'] = $ue;
            $rs['data']['coupon']  = $uc;
            return response()->json($rs);
        } 
        // 重新入栈
        RedisService::lpush($key,$redis_envelop);        

        $rs['msg'] = $flag['msg']; 
        
        
        
        return response()->json($rs);
        
        
    }
}
